package com.ruoyi.web.controller.system.fuw.wx;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.fuw.domain.FuwCar;
import com.ruoyi.fuw.domain.FuwMessage;
import com.ruoyi.fuw.domain.FuwPerson;
import com.ruoyi.fuw.domain.FuwTasks;
import com.ruoyi.fuw.service.IFuwCarService;
import com.ruoyi.fuw.service.IFuwMessageService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.CollationKey;
import java.text.Collator;
import java.util.*;

/**
 * Wx聊天会话Controller
 *
 * @author zjh
 * @date 2021-10-09
 */
@RestController
@RequestMapping("/api/wx/chat")
public class WxFuwChatController extends BaseController {

    @Autowired
    private IFuwMessageService fuwMessageService;

    @Autowired
    private IFuwCarService fuwCarService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询 - 可聊天人员信息
     * uid : 别人的ID
     * username : 别人的姓名
     * face : 别人的头像
     * msg : 最新消息
     * time : 最新消息的时间
     * tisNum : 未读消息数量
     *
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:list')")
    @GetMapping("/list/msg")
    public AjaxResult listUnread()
    {
        // 查询全部的用户信息并将自己排除
        SysUser sysUserNew = new SysUser();
        sysUserNew.setDeptId(113L);
        sysUserNew.setStatus("0");
        List<SysUser> userList = userService.selectList(sysUserNew);
        // 根据ID排序
        Collections.sort(userList, new Comparator<SysUser>() {
            Collator collator = Collator.getInstance(Locale.CHINA);
            @Override
            public int compare(SysUser o1, SysUser o2) {
                CollationKey key1 = collator.getCollationKey(o1.getUserName());
                CollationKey key2 = collator.getCollationKey(o2.getUserName());
                return key1.compareTo(key2);
            }
        });
        // 将自己排除
        for(SysUser sysUser:userList){
            if(sysUser.getUserName().equals(getUsername())){
                userList.remove(sysUser);
            }
        }

        // 查询对应用户的聊天记录：
        // 1、获取最新消息记录和时间； 2、获取未读消息数量
        List<Map<String,Object>> listChatMap = new ArrayList<Map<String,Object>>();

        for(SysUser sysUser: userList){
            // 1、查询对应用户和自己的消息记录
            FuwMessage fuwMessageFrom = new FuwMessage();
            fuwMessageFrom.setFrom(String.valueOf(sysUser.getUserName()));
            fuwMessageFrom.setTo(getUsername());
            List<FuwMessage> listMsg = fuwMessageService.selectFuwMessageList(fuwMessageFrom);

            // 根据发出时间进行倒叙排列
            Collections.sort(listMsg, new Comparator<FuwMessage>() {
                Collator collator = Collator.getInstance(Locale.CHINA);
                @Override
                public int compare(FuwMessage o1, FuwMessage o2) {
                    CollationKey key1 = collator.getCollationKey(String.valueOf(o1.getChatTime().getTime()));
                    CollationKey key2 = collator.getCollationKey(String.valueOf(o2.getChatTime().getTime()));
                    return key1.compareTo(key2);
                }
            });

            // 2、筛选出未读消息数量
            Integer num = 0;
            for(FuwMessage fuwMessage:listMsg){
                if(fuwMessage.getChatType().equals(0)){
                    num ++;
                }
            }

            // 将相应内容存放入map中
            Map<String, Object> mapNew = new HashMap<>();
            mapNew.put("uid", sysUser.getUserName());
            mapNew.put("username", sysUser.getNickName());
            mapNew.put("face", "http://localhost/dev-api" + sysUser.getAvatar());
            if(listMsg.size() > 0){
                mapNew.put("msg", listMsg.get(0).getChatText());
                mapNew.put("time", listMsg.get(0).getChatTime());
            }else{
                mapNew.put("msg", "新朋友加入聊天");
                mapNew.put("time", DateUtils.parseDate(DateUtils.getTime()));
            }
            mapNew.put("tisNum", num);

            listChatMap.add(mapNew);
        }
        System.out.println("listMap =" + listChatMap.toString());

        return AjaxResult.success(listChatMap);
    }

    /**
     * 查询消息记录列表
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:list')")
    @GetMapping("/list/message")
    public AjaxResult listMessageAll(SysUser sysUser)
    {
        List<FuwMessage> listAll = new ArrayList<>();
        List<FuwMessage> listFrom = new ArrayList<>();
        List<FuwMessage> listTo = new ArrayList<>();

        FuwMessage fuwMessageFrom = new FuwMessage();
        fuwMessageFrom.setFrom(sysUser.getUserName());
        fuwMessageFrom.setTo(getUsername());
        listFrom = fuwMessageService.selectFuwMessageList(fuwMessageFrom);
        listAll.addAll(listFrom);
        FuwMessage fuwMessageTo = new FuwMessage();
        fuwMessageTo.setFrom(getUsername());
        fuwMessageTo.setTo(sysUser.getUserName());
        listTo = fuwMessageService.selectFuwMessageList(fuwMessageTo);
        listAll.addAll(listTo);

        Collections.sort(listAll, new Comparator<FuwMessage>() {
            Collator collator = Collator.getInstance(Locale.CHINA);
            @Override
            public int compare(FuwMessage o1, FuwMessage o2) {
                CollationKey key1 = collator.getCollationKey(String.valueOf(o1.getChatTime().getTime()));
                CollationKey key2 = collator.getCollationKey(String.valueOf(o2.getChatTime().getTime()));
                return key1.compareTo(key2);
            }
        });

        return AjaxResult.success(listAll);
    }

}
